/**初始化硬件设备**/
var  CODER_ALAW		        = 0;
var  CODER_PCM		        = 1;
var  CODER_SPEEX            = 20;

var  hdl = -1;

var	 UBOX_STATE_RINGING     = 2;			//振铃态，表示已检测到线路振铃信号，如果振铃停止，则将触发 UBOX_EVENT_RESET 事件，并汇报 UBOX_STATE_RESET 状态。
var	 UBOX_STATE_HOOK_OFF    = 3;			//摘机态，
var  UBOX_STATE_IDLE        = 5;              //空闲中，挂机

var  ubox={                    //全局声明
    lines:[],
    linenum:0
};
var  ws = null;
function  Get_Error(result) {
    var error ="";
    switch( result) {
        case 0:
            error = "操作成功";
            break;
        case -1:
            error = "系统错误";
            break;
        case -2:
            error = "无此设备";
            break;
        case -3:
            error = " 非法的 UBOX_HANDLE";
            break;
        case -4:
            error = "非法参数";
            break;
        case -10:
            error = "未能创建目录";
            break;
        case -11:
            error = " 未能创建录音文件";
            break;
        case -12:
            error = "不支持的语音编码";
            break;
        case -6:
            error = "错误的工作模式";
            break;
        case -5:
            error = "发生异常";
            break;
        case -13:
            error = "设备忙";
            break;
        case -7:
            error = " ubox设备尚未打开";
            break;
        default:
            error = "未定义的错误码";
            break;
    }
    return error;
}

/**初始化连接参数**/
$(function() {
    if(window.WebSocket) {
        ws = new WebSocket(wsproto+'127.0.0.1:8054/');
        ws.onopen = function(ev)  { console.log("open:"+JSON.stringify(ev)) };
        ws.onerror = function(ev) { console.log("websocket error:"+JSON.stringify(ev)); $JuXue.n_danger("当前没有连接设备");$("#divoceType").text("当前设备异常"); };
        ws.onclose = function(ev) { console.log("websocket close:"+JSON.stringify(ev)); $JuXue.n_danger("当前连接设备已经关闭"); $("#divoceType").text("当前设备异常"); ws = null;};
        ws.onmessage = function(ev) {
            var msg = eval('(' + ev.data + ')');
            if(msg.event == "plugin") {
                Ubox_Plug_In(msg.handle);
            } else if(msg.event == "hookoff") { //摘机
                Ubox_hookoff(msg.handle);
            } else if(msg.event == "hookup") { //挂机
                Ubox_hookon(msg.handle);
            } else if(msg.event == "ring") {   //来电振岭
                var uboxhdl11 = msg.handle;
                ubox.lines[uboxhdl11].state =  UBOX_STATE_RINGING;
            } else if(msg.event == "hang") {  //如果电话线不可用了
                ubox_HangIng(msg.handle);
            } else if(msg.event == "callerId") {   //来电获取的来电号码
                console.log("来电获取的来电号码: "+msg.callernumber);
                $("#in_phone_num").val(msg.callernumber);
            } else if(msg.event == "deviceAlarm") {
                $JuXue.n_danger("录音设备警告，请重启软件");
                $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
            } else if(msg.event == "ringCancel") {  //振铃取消
                console.log("振铃取消");
                var uboxhdl22 = msg.handle;
                ubox.lines[uboxhdl22].state =  UBOX_STATE_IDLE;
            }else if(msg.event == "deviceError") {
                $JuXue.n_danger("录音设备警告，请重启软件");
                $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
            }  else if(msg.event == "CallOutFinish") {
                console.log("软件拨号完成 handle:"+msg.handle);
                /**拨号完成开始录音**/
                ubox_RecordFile();
            } else if(msg.event == "plugout") {
                var uboxhdl33 = msg.handle;
                 //设备拔出来;
                ubox.lines[uboxhdl33].handle = -1;
                ubox.lines[uboxhdl33] = undefined;
                ubox.linenum -= 1;
                $JuXue.n_danger(uboxhdl33+"录音设备 拨出");
                $("#divoceType").text("当前设备异常");
                hdl=-1;
            } else if(msg.event == "joined") {
                console.log("connect websocket ok");
                var msg = {"event": "getinfo"};
                websocket_send_msg(JSON.stringify(msg));
            } else if(msg.event == "left") {
                console.log("disconnect websocket ok");
                $JuXue.n_danger("websocket disconnect ok");
            }else if(msg.event == "getinfo") {
                if(msg.channels.length > 0) {
                    for(var i=0;i<msg.channels.length;i++) {
                        Ubox_Plug_In(msg.channels[i].handle);
                        if(msg.channels[i].deviceError)
                            ubox_DeviceError(msg.channels[i].handle);
                        if(msg.channels[i].deviceAlarm)
                            ubox_DeviceAlarm(msg.channels[i].handle);
                    }
                } else {
                    console.log("no usb device  plugin");
                    $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
                }
            } else if(msg.event == "notify") {
                console.log(msg.errorType+" handle:"+msg.handle +" "+Get_Error(msg.result));
            } else if(msg.event == "answer") {
                if( msg.type == "GetProductID") {
                    if(msg.result == "1") {
                        console.log("USB设备FI3102A");
                        $("#devicedType").text("USB设备FI3102A");
                        ubox.lines[msg.handle].productid = 1;
                    } else if(msg.result == "2") {
                        console.log("USB设备是FI3002B");
                        $("#devicedType").text("USB设备FI3002B");
                        ubox.lines[msg.handle].productid = 2;
                    } else if(msg.result == "3") {
                        console.log("USB设备是FI3001B");
                        $("#devicedType").text("USB设备FI3001B");
                        ubox.lines[msg.handle].productid = 3;
                    } else if(msg.result == "4") {
                        console.log("USB设备是FI3101A");
                        $("#devicedType").text("USB设备FI3101A");
                        ubox.lines[msg.handle].productid = 4;
                    } else if(msg.result == "8") {
                        console.log("USB设备是无线设备");
                        $("#devicedType").text("USB无线设备");
                        ubox.lines[msg.handle].productid = 8;
                    }
                }
            }else if (msg.event == "dtmfdown"){
                //电话拨号
                //console.log("模拟按键的号码是:"+(msg.dtmfkey-48));
            }  else {
                console.log(ev.data);
            }
        };
    } else {
        console.log("当前浏览器不支持websocket");
        $JuXue.n_danger("当前浏览器不支持websocket");
        $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
    }
});
function websocket_send_msg(msg) {
    ws.send(msg);
}
/**插入设备初始化**/
function Ubox_Plug_In(uboxhdl) {
    if(ubox.linenum == 2) return;
    ubox.linenum++;
    if( ubox.lines[uboxhdl] == undefined ){ubox.lines[uboxhdl] = {};}
    ubox.lines[uboxhdl].handle = uboxhdl;
    ubox.lines[uboxhdl].callernumber = "";
    ubox.lines[uboxhdl].dtmfkyes = "";
    ubox.lines[uboxhdl].lineid = ubox.linenum;
    ubox.lines[uboxhdl].state =  UBOX_STATE_IDLE;
    ubox.lines[uboxhdl].record = 0;
    ubox.lines[uboxhdl].productid = 0;
    if(ubox.linenum == 1) {hdl = ubox.lines[uboxhdl].handle;}
    var msg = {
        "event": "GetProductID",
        "handle": uboxhdl
    };
    /*如果失败， 在notify 消息中，会报错的*/
    websocket_send_msg(JSON.stringify(msg));
}
/**电话没有连接好**/
function ubox_HangIng(uboxhdl) {
    console.log(" 电话未连接好");
    $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
    if( ubox.lines[uboxhdl].record  == 1) {
        ubox.lines[uboxhdl].record = 0;
        if(hdl != -1) {
            var msg = {
                "event": "StopRecord",
                "handle": uboxhdl
            };
            /* 如果失败， 在notify 消息中，会报错的*/
            websocket_send_msg(JSON.stringify(msg));
            console.log("已经停止录音");
        }
    }
}
/**摘取电话机录音的事件**/
function Ubox_hookoff(uboxhdl) {
    var curDate = new Date();
    var rec_name = "IN_"+userName+curDate.getFullYear()+(curDate.getMonth()+1)+curDate.getDate()+curDate.getHours()+curDate.getMinutes()+curDate.getSeconds()+".wav";
    /**判断摘取电话的目的(接听还是打电话)**/
    if (ubox.lines[uboxhdl].state ==  UBOX_STATE_RINGING){
        //如果是来电
        if(ubox.lines[uboxhdl].record == 0) {
            var msg = {
                "event": "RecordFile",
                "handle": uboxhdl,
                "filename":rec_name,
                "codec":  CODER_ALAW
            };
            console.log("来电铃声录音");
            //如果失败， 在notify 消息中，会报错的
            websocket_send_msg(JSON.stringify(msg));
            ubox.lines[uboxhdl].record = 1;
            $("#recordUrl").val(rec_name); //录音文件再本地的位置
        }
    }
    //把电话机的状态转变成摘机状态
    ubox.lines[uboxhdl].state =  UBOX_STATE_HOOK_OFF;
}
/**拨打电话录音**/
function ubox_RecordFile() {
    var curDate = new Date();
    var rec_name = "Out_"+userName+curDate.getFullYear()+(curDate.getMonth()+1)+curDate.getDate()+curDate.getHours()+curDate.getMinutes()+curDate.getSeconds()+".wav";
    if(hdl != -1) {
        var msg = {
            "event": "RecordFile",
            "handle": hdl,
            "filename":rec_name,
            "codec":  CODER_SPEEX
        };
        console.log("开始录音...");
        //如果失败， 在notify 消息中，会报错的
        websocket_send_msg(JSON.stringify(msg));
        $("#recordUrl").val(rec_name); //录音文件再本地的位置
    }
}

var timer = 0;
/**拨号**/
function ubox_dialnum(szCode) {
    var val=$('input:radio[name="dialcodeCode"]:checked').val();
    szCode = val+szCode;
    if(hdl != -1) {
        if(	 ubox.lines[hdl].state ==  UBOX_STATE_HOOK_OFF) {
            var msg = {
                "event": "SendDtmf",
                "handle": hdl,
                "dtmf":szCode
            };
            console.log("拨号:"+szCode);
            /*如果失败， 在notify 消息中，会报错的 */
            websocket_send_msg(JSON.stringify(msg));
        } else {
            $JuXue.n_danger("请摘起电话机");
            console.log("请摘起电话机");
            return;
        }
    }else{
        $JuXue.n_danger("当前设备运行异常");
        return;
    }
    $("#dialcodeNumid").hide();
    /**打电话计时**/
    var  minute=0;
    var second=0;//时间默认值
    timer = window.setInterval(function(){
        var min = 0;
        second++;
        if (second <= 9) {
            second = '0' + second;
        }
        if (second >=59){
            minute++;
            second = 0;
        }
        if (minute <= 9){
            min = '0' + minute;
        }else{
            min = minute;
        }
        $('#minute_show').html('<s></s>'+min+'分');
        $('#second_show').html('<s></s>'+second+'秒');

    }, 1000);
}

/**挂机事件**/
function Ubox_hookon(uboxhdl) {
    var outdata = "设备"+uboxhdl;
    ubox.lines[uboxhdl].state =  UBOX_STATE_IDLE;
    console.log(outdata+" 挂机");
    ubox.lines[uboxhdl].record = 0;
    if(hdl != -1) {
        var msg = {
            "event": "StopRecord",
            "handle": uboxhdl
        };
        /* 如果失败， 在notify 消息中，会报错的 */
        websocket_send_msg(JSON.stringify(msg));
        console.log("已经停止录音");
        //清除定时器
        clearInterval(timer);
        //关闭打电话的界面
        $("#phone-modal").modal('hide');
        //上传录音的服务器
        var filename =  $("#recordUrl").val();
        console.log("录音文件的地址："+filename);
        console.log("上传地址："+record_url);
        UploadfileToserverEx(record_url,"customer",filename);
        //暂不清除本地录音(保留记录)
    }else{
        console.log(outdata+" 挂机 出现失误");
        $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
    }
}

/**文件上传**/
function UploadfileToserverEx(url, paramname, filename) {
    var msg = {
        "event": "UploadFileEx",
        "url":url,
        "paramname":paramname,
        "filename":filename
    };
    console.log("上传录音文件");
    /*如果失败， 在notify 消息中，会报错的*/
    websocket_send_msg(JSON.stringify(msg));
    /**上传完成2秒之后 增加录音记录**/
    setTimeout('uploadRecoird()',2000);
}
/**三秒之后 增加录音记录**/
function uploadRecoird(){
    var url = $("#recordUrl").val();
    var uid =  $("#cus_phone_uid").val();
    var uitype = $("#cus_uid_type").val();
    var num = $("#in_phone_num").val();
    var json = {"rname":url,"uid":uid,"utype":uitype,"phone":num};
    //判断录音上传得位置
    var data = sessionStorage.getItem("typeDia");
    if (data == "1") {
        //我得客户电话打来
        $.post(ctx+"myCustomer/uploadRecordSec",json,function (r) {console.log(r);});
    }else{
        //电话任务
        $.post(ctx+"SalePhone/updateTaskPhoneRecord",{spId:uid,spRecordUrl:url},function (r) {console.log(r);$JuXue.refreshTable("phonePersonTaskTable");});
    }
    //清除上一次通话的信息
    $("#recordUrl").val('');
    $("#cus_phone_uid").val('');$("#cus_uid_type").val('');$("#in_phone_num").val('');
    //
    // //删除通话的文件
    // var msg = {
    //     "event": "UBOXDeletefile",
    //     "filename":url
    // };
    // websocket_send_msg(JSON.stringify(msg));
}

function ubox_DeviceAlarm(uboxhdl) {
    var outdata = "设备"+uboxhdl;
    console.log(outdata+" 警告，重启软件");
    $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
}

function ubox_DeviceError(uboxhdl) {
    var outdata = "设备"+uboxhdl;
    console.log(outdata+" 错误，重启软件");
    $("#divoceType").text("当前设备异常").removeClass("btn-success").addClass("btn-danger");
}
